package am.fp
{        
  import flash.ui.ContextMenu;
  import flash.ui.ContextMenuItem;
  import flash.events.ContextMenuEvent;

  import am.fp.LocaleManager;
  import am.fp.FPDispatcher;
  import am.fp.TextSelection;
  import am.fp.events.StatusEvent;
  import am.fp.events.TextSelectionEvent;

  /**
   * Custom context menu.
   */
  public class FPContextMenu
  {
    static protected var m_instance: FPContextMenu;
    
    protected var m_menu: ContextMenu;
    protected var m_itemAbout: ContextMenuItem;
    protected var m_itemCopy: ContextMenuItem;

    static public function get menu(): ContextMenu    { return instance.m_menu; }
    
    static public function get instance(): FPContextMenu
    {
      if (m_instance == null)
        m_instance = new FPContextMenu(new SingletonEnforcer);
      return m_instance;
    }
    
    /**
     * Constructor.
     */
    public function FPContextMenu(enforcer: SingletonEnforcer)
    {
      if (enforcer == null)
        throw new Error("This class is a singleton so it can't be instantiated");
      
      m_menu = new ContextMenu();
      m_menu.hideBuiltInItems();

      // add "About" item
      m_itemAbout = new ContextMenuItem(LocaleManager.instance.getString("IDS_ABOUT_FP"), false, true, true);
      m_itemAbout.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onAbout, false, 0, true);
      m_menu.customItems.push(m_itemAbout);
      
      // add "Copy" item
      m_itemCopy = new ContextMenuItem(LocaleManager.instance.getString("IDS_COPY_SEL_TEXT"), true, true, false);
      m_itemCopy.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onCopySelectedText, false, 0, true);
      m_menu.customItems.push(m_itemCopy);
      
      // listen for text selection event change
      TextSelection.instance.addEventListener(TextSelectionEvent.CHANGE, onChangeTextSelection, false, 0, true);
    }
    
    protected function onAbout(e: ContextMenuEvent): void
    {
      FPDispatcher.instance.dispatchEvent(new StatusEvent(StatusEvent.CHANGE, StatusEvent.SHOW_ABOUT));
    }
    
    protected function onCopySelectedText(e: ContextMenuEvent): void
    {
      FPDispatcher.instance.dispatchEvent(new TextSelectionEvent(TextSelectionEvent.SET_CLIPBOARD));
    }
    
    protected function onChangeTextSelection(e: TextSelectionEvent): void
    {
      m_itemCopy.visible = (e.pageNum != -1);
    }
  }
}

/**
 * Class which disables the call to the constrcutor of FPContextMenu, which is a singleton
 */
class SingletonEnforcer{}
